package com.zxy.controller;


import com.zxy.common.JwtUtil;
import com.google.code.kaptcha.Producer;
import com.zxy.common.result.Result;
import com.zxy.mapper.SysUserMapper;
import com.zxy.pojo.entity.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

/**
 * 登录认证接口
 */
@RestController
@RequestMapping
public class AuthController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private Producer kaptchaProducer;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 生成验证码接口
     */
    @GetMapping("/captchaImage")
    public Map<String, Object> getCaptchaImage(HttpServletRequest request, HttpServletResponse response) {
        log.info("Received captcha image request from: {}", request.getRemoteAddr());

        // 生成验证码文本
        String captchaText = kaptchaProducer.createText();
        // 生成 UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        log.info("Generated captcha: {} with UUID: {}", captchaText, uuid);

        // 生成验证码图片并转为base64
        BufferedImage image = kaptchaProducer.createImage(captchaText);
        String imgBase64 = "";
        try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", os);
            imgBase64 = Base64.getEncoder().encodeToString(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, Object> result = new HashMap<>();
        result.put("msg", "操作成功");
        result.put("img", imgBase64);
        result.put("code", 200);
        result.put("uuid", uuid);
        // 直接将验证码文本也返回（仅用于测试，生产环境不应这样做）
        result.put("captchaText", captchaText);
        return result;
    }




    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginInfo, HttpServletRequest request) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        String captcha = loginInfo.get("captcha");
        String uuid = loginInfo.get("uuid");

        log.info("Login attempt for username: {}", username);
        log.info("Provided password length: {}", password != null ? password.length() : "null");

        if (username == null || username.isEmpty()) {
            log.warn("Username is null or empty");
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 400);
            errorResult.put("message", "用户名不能为空");
            errorResult.put("data", null);
            return errorResult;
        }

        if (password == null || password.isEmpty()) {
            log.warn("Password is null or empty");
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 400);
            errorResult.put("message", "密码不能为空");
            errorResult.put("data", null);
            return errorResult;
        }

        // 从数据库查询用户信息
        SysUser user = sysUserMapper.selectUserByUserName(username);
        log.info("Database query completed, user found: {}", user != null);

        if (user == null) {
            log.warn("Username '{}' not found in database", username);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 400);
            errorResult.put("message", "用户名或密码错误");
            errorResult.put("data", null);
            return errorResult;
        }

        log.info("User details - userId: {}, username: {}, stored password: {}", 
                 user.getUserId(), user.getUserName(), user.getPassword());
        log.info("Password comparison - stored: '{}', provided: '{}'", user.getPassword(), password);
        log.info("Password equals result: {}", user.getPassword() != null ? user.getPassword().equals(password) : "null");

        // 验证密码（这里需要根据实际的密码加密方式进行验证）
        // 假设密码是明文存储的，实际项目中应该使用加密方式
        // 同时处理user.getPassword()可能为null的情况
        if (user.getPassword() != null && user.getPassword().equals(password)) {
            log.info("Password validation successful for user: {}", username);
            // 生成 JWT Token
            redisTemplate.opsForValue().set("user", username);
            String token = jwtUtil.generateToken(username);

            // 将用户信息保存到Session中
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            // 可以保存更多用户信息
            session.setAttribute("userInfo", createUserInfo(username));

            log.info("User {} login successful", username);
            Map<String, Object> successResult = new HashMap<>();
            successResult.put("msg", "操作成功");
            successResult.put("code", 200);
            successResult.put("token", token);
            return successResult;
        } else {
            log.warn("Invalid password for user: '{}'", username);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 400);
            errorResult.put("message", "用户名或密码错误");
            errorResult.put("data", null);
            return errorResult;
        }
    }
    // 添加创建用户信息的方法
    private Map<String, Object> createUserInfo(String username) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", username);
        // 可以添加更多用户相关信息
        userInfo.put("loginTime", new Date());
        return userInfo;
    }



    /**
     * 退出登录接口
     * @return 退出成功响应
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        log.info("Received logout request");

        try {
            // 清除session中的用户信息
            HttpSession session = request.getSession(false);
            if (session != null) {
                String username = (String) session.getAttribute("username");
                if (username != null) {
                    log.info("User {} logout successful", username);
                    session.invalidate(); // 使session失效
                }
            }

            // 清除Redis中的用户信息（如果有的话）
            redisTemplate.delete("user");

            // 返回退出成功响应
            return Result.success("退出成功");
        } catch (Exception e) {
            log.error("Logout error: {}", e.getMessage());
            return Result.error("退出失败");
        }
    }


    /**
     * 获取用户信息接口
     */
    @GetMapping("/getInfo")
    public Map<String, Object> getInfo() {
        log.info("Get user info request received");

        Map<String, Object> result = new HashMap<>();
        result.put("msg", "操作成功");
        result.put("code", 200);

        // 添加权限信息
        List<String> permissions = Arrays.asList("*:*:*");
        result.put("permissions", permissions);

        // 添加角色信息
        List<String> roles = Arrays.asList("admin");
        result.put("roles", roles);

        // 构建用户信息
        Map<String, Object> user = new HashMap<>();
        user.put("createBy", "admin");
        user.put("createTime", "2021-03-31 03:12:10");
        user.put("updateBy", null);
        user.put("updateTime", null);
        user.put("userId", 1);
        user.put("deptId", 103);
        user.put("userName", "admin");
        user.put("nickName", "admin");
        user.put("email", "admin@163.com");
        user.put("phonenumber", "15888888888");
        user.put("sex", "1");
        user.put("avatar", "");
        user.put("salt", null);
        user.put("status", "0");
        user.put("delFlag", "0");
        user.put("loginIp", "127.0.0.1");
        user.put("loginDate", "2021-03-31T03:12:10.000+0800");

        // 构建部门信息
        Map<String, Object> dept = new HashMap<>();
        dept.put("createBy", null);
        dept.put("createTime", null);
        dept.put("updateBy", null);
        dept.put("updateTime", null);
        dept.put("deptId", 103);
        dept.put("parentId", 101);
        dept.put("ancestors", null);
        dept.put("deptName", "研发部门");
        dept.put("orderNum", "1");
        dept.put("leader", "若依");
        dept.put("phone", null);
        dept.put("email", null);
        dept.put("status", "0");
        dept.put("delFlag", null);
        dept.put("parentName", null);
        dept.put("users", new ArrayList<>());
        dept.put("children", new ArrayList<>());
        user.put("dept", dept);

        // 构建角色信息
        List<Map<String, Object>> userRoles = new ArrayList<>();
        Map<String, Object> role = new HashMap<>();
        role.put("createBy", null);
        role.put("createTime", null);
        role.put("updateBy", null);
        role.put("updateTime", null);
        role.put("roleId", 1);
        role.put("roleName", "超级管理员");
        role.put("roleKey", "admin");
        role.put("roleSort", "1");
        role.put("dataScope", "1");
        role.put("menuCheckStrictly", false);
        role.put("deptCheckStrictly", false);
        role.put("status", "0");
        role.put("delFlag", null);
        role.put("flag", false);
        role.put("menuIds", null);
        role.put("deptIds", null);
        role.put("admin", true);
        userRoles.add(role);
        user.put("roles", userRoles);

        user.put("roleIds", null);
        user.put("admin", true);

        result.put("user", user);

        return result;
    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    //@ApiOperation("获取路由信息")
    /**
     * 获取路由信息（格式化返回，与原 JSON 字节一致）
     */
    @GetMapping("/getRouters")
    public String getRouters() {
        return "{" +
                "\"msg\":\"操作成功\"," +
                "\"code\":200," +
                "\"data\":[" +
                // 1. 首页
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"首页\",\"icon\":\"icon_menu_home\",\"noCache\":false},\"children\":[{\"name\":\"Index\",\"path\":\"index\",\"hidden\":false,\"component\":\"indexHome\",\"meta\":{\"title\":\"首页\",\"icon\":\"icon_menu_home\",\"noCache\":false}}]}," +
                // 2. 线索管理
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"线索管理\",\"icon\":\"icon_menu_xsgl\",\"noCache\":false},\"children\":[{\"name\":\"Clue\",\"path\":\"clue\",\"hidden\":false,\"component\":\"clues/clue/index\",\"meta\":{\"title\":\"线索管理\",\"icon\":\"icon_menu_xsgl\",\"noCache\":false}}]}," +
                // 3. 商机管理
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"商机管理\",\"icon\":\"icon_menu_sjgl\",\"noCache\":false},\"children\":[{\"name\":\"Business\",\"path\":\"business\",\"hidden\":false,\"component\":\"clues/business/index\",\"meta\":{\"title\":\"商机管理\",\"icon\":\"icon_menu_sjgl\",\"noCache\":false}}]}," +
                // 4. 合同管理
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"合同管理\",\"icon\":\"icon_menu_htgl\",\"noCache\":false},\"children\":[{\"name\":\"Contract\",\"path\":\"contract\",\"hidden\":false,\"component\":\"clues/contract/index\",\"meta\":{\"title\":\"合同管理\",\"icon\":\"icon_menu_htgl\",\"noCache\":false}}]}," +
                // 5. 活动管理
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"活动管理\",\"icon\":\"icon_menu_hdgl\",\"noCache\":false},\"children\":[{\"name\":\"Activity\",\"path\":\"activity\",\"hidden\":false,\"component\":\"clues/activity/index\",\"meta\":{\"title\":\"活动管理\",\"icon\":\"icon_menu_hdgl\",\"noCache\":false}}]}," +
                // 6. 课程管理
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"课程管理\",\"icon\":\"icon_menu_kcgl\",\"noCache\":false},\"children\":[{\"name\":\"Course\",\"path\":\"course\",\"hidden\":false,\"component\":\"clues/course/index\",\"meta\":{\"title\":\"课程管理\",\"icon\":\"icon_menu_kcgl\",\"noCache\":false}}]}," +
                // 7. 统计分析
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"统计分析\",\"icon\":\"icon_menu_tjfx\",\"noCache\":false},\"children\":[{\"name\":\"CountAnalysis\",\"path\":\"countAnalysis\",\"hidden\":false,\"component\":\"clues/countAnalysis/index\",\"meta\":{\"title\":\"统计分析\",\"icon\":\"icon_menu_tjfx\",\"noCache\":false}}]}," +
                // 8. 转派管理
                "{\"path\":\"/\",\"hidden\":false,\"component\":\"Layout\",\"meta\":{\"title\":\"转派管理\",\"icon\":\"example\",\"noCache\":false},\"children\":[{\"name\":\"TransferManage\",\"path\":\"transferManage\",\"hidden\":false,\"component\":\"clues/transferManage/index\",\"meta\":{\"title\":\"转派管理\",\"icon\":\"example\",\"noCache\":false}}]}," +
                // 9. 系统管理
                "{\"name\":\"System\",\"path\":\"/system\",\"hidden\":false,\"redirect\":\"noRedirect\",\"component\":\"Layout\",\"alwaysShow\":true,\"meta\":{\"title\":\"系统管理\",\"icon\":\"icon_menu_xtgl\",\"noCache\":false},\"children\":[" +
                // 9.1 权限管理
                "{\"name\":\"Permission\",\"path\":\"permission\",\"hidden\":false,\"redirect\":\"noRedirect\",\"component\":\"ParentView\",\"alwaysShow\":true,\"meta\":{\"title\":\"权限管理\",\"icon\":\"icon_menu_qxgl\",\"noCache\":false},\"children\":[" +
                "{\"name\":\"User\",\"path\":\"user\",\"hidden\":false,\"component\":\"system/user/index\",\"meta\":{\"title\":\"用户管理\",\"icon\":\"user\",\"noCache\":false}}," +
                "{\"name\":\"Role\",\"path\":\"role\",\"hidden\":false,\"component\":\"system/role/index\",\"meta\":{\"title\":\"角色管理\",\"icon\":\"peoples\",\"noCache\":false}}," +
                "{\"name\":\"Menu\",\"path\":\"menu\",\"hidden\":false,\"component\":\"system/menu/index\",\"meta\":{\"title\":\"菜单管理\",\"icon\":\"tree-table\",\"noCache\":false}}," +
                "{\"name\":\"Dept\",\"path\":\"dept\",\"hidden\":false,\"component\":\"system/dept/index\",\"meta\":{\"title\":\"部门管理\",\"icon\":\"tree\",\"noCache\":false}}," +
                "{\"name\":\"Post\",\"path\":\"post\",\"hidden\":false,\"component\":\"system/post/index\",\"meta\":{\"title\":\"岗位管理\",\"icon\":\"post\",\"noCache\":false}}" +
                "]}," +
                // 9.2 其他子项
                "{\"name\":\"Dict\",\"path\":\"dict\",\"hidden\":false,\"component\":\"system/dict/index\",\"meta\":{\"title\":\"字典管理\",\"icon\":\"icon_menu_zdgl\",\"noCache\":false}}," +
                "{\"name\":\"Clew\",\"path\":\"clew\",\"hidden\":false,\"component\":\"system/clew/index\",\"meta\":{\"title\":\"线索配置\",\"icon\":\"icon_menu_xspz\",\"noCache\":false}}," +
                "{\"name\":\"Opportunity\",\"path\":\"opportunity\",\"hidden\":false,\"component\":\"system/opportunity/index\",\"meta\":{\"title\":\"商机配置\",\"icon\":\"icon_menu_sjpz\",\"noCache\":false}}," +
                "{\"name\":\"NoticeCenter\",\"path\":\"noticeCenter\",\"hidden\":false,\"component\":\"system/noticeCenter/index\",\"meta\":{\"title\":\"通知中心\",\"icon\":\"icon_menu_tzzx\",\"noCache\":false}}," +
                // 9.3 日志管理（隐藏一级）
                "{\"name\":\"Log\",\"path\":\"log\",\"hidden\":true,\"redirect\":\"noRedirect\",\"component\":\"ParentView\",\"alwaysShow\":true,\"meta\":{\"title\":\"日志管理\",\"icon\":\"log\",\"noCache\":false},\"children\":[" +
                "{\"name\":\"Operlog\",\"path\":\"operlog\",\"hidden\":false,\"component\":\"monitor/operlog/index\",\"meta\":{\"title\":\"操作日志\",\"icon\":\"form\",\"noCache\":false}}," +
                "{\"name\":\"Logininfor\",\"path\":\"logininfor\",\"hidden\":false,\"component\":\"monitor/logininfor/index\",\"meta\":{\"title\":\"登录日志\",\"icon\":\"logininfor\",\"noCache\":false}}" +
                "]}," +
                // 9.4 系统日志（可见）
                "{\"name\":\"SystemLog\",\"path\":\"systemLog\",\"hidden\":false,\"component\":\"system/systemLog/index\",\"meta\":{\"title\":\"系统日志\",\"icon\":\"icon_menu_xtrz\",\"noCache\":false}}" +
                "]}" +
                "]" +
                "}";
    }
    // 辅助方法：创建路由对象
    private Map<String, Object> createRouter(String path, String component, String title, String icon, Map<String, Object> child) {
        Map<String, Object> router = new HashMap<>();
        router.put("path", path);
        router.put("hidden", false);
        router.put("component", component);

        Map<String, Object> meta = new HashMap<>();
        meta.put("title", title);
        meta.put("icon", icon);
        meta.put("noCache", false);
        router.put("meta", meta);

        List<Map<String, Object>> children = new ArrayList<>();
        children.add(child);
        router.put("children", children);

        return router;
    }

    // 辅助方法：创建子路由对象
    private Map<String, Object> createChildRoute(String name, String path, String component, String title, String icon) {
        Map<String, Object> child = new HashMap<>();
        child.put("name", name);
        child.put("path", path);
        child.put("hidden", false);
        child.put("component", component);

        Map<String, Object> meta = new HashMap<>();
        meta.put("title", title);
        meta.put("icon", icon);
        meta.put("noCache", false);
        child.put("meta", meta);

        return child;
    }

    // 辅助方法：创建简单路由对象
    private Map<String, Object> createSimpleRoute(String name, String path, String component, String title, String icon) {
        Map<String, Object> route = new HashMap<>();
        route.put("name", name);
        route.put("path", path);
        route.put("hidden", false);
        route.put("component", component);

        Map<String, Object> meta = new HashMap<>();
        meta.put("title", title);
        meta.put("icon", icon);
        meta.put("noCache", false);
        route.put("meta", meta);

        return route;
    }
}